<template>
  <!-- 组织人员选择器弹窗 -->
  <el-dialog
    title="通讯录"
    :visible.sync="userBookVisible"
    width="40%"
    append-to-body
    @close="handleClose">

    <div class="organization-selector">
      <!-- 左侧组织树 -->
      <div class="organization-tree">
        <el-input
          placeholder="请输入内容"
          v-model="filterText"
          clearable>
        </el-input>

        <el-tree
          ref="orgTree"
          :data="orgTreeData"
          :props="treeProps"
          node-key="id"
          :default-expanded-keys="expandedKeys"
          :filter-node-method="filterNode"
          @check-change="handleCheckChange">
                          <span class="custom-tree-node" slot-scope="{ node, data }">
                            <el-checkbox v-if="data.checkbox" v-model='node.checked'></el-checkbox>
                            <svg-icon v-if="!data.checkbox" :icon-class="'tree'" style="width: 25px;"/>
                            <svg-icon v-else :icon-class="'user'" style="width: 25px;"/>
                            <span>{{ node.label }}</span>
                        </span>

        </el-tree>
      </div>

      <!-- 右侧已选人员 -->
      <div class="selected-panel">
        <div class="selected-title">已选对象({{ selectedUsers.length }})</div>
        <div class="selected-list">
          <div v-if="selectedUsers.length === 0" class="empty-selected">
            暂无选择
          </div>
          <div v-else>
            <div v-for="user in selectedUsers" :key="user.id" class="selected-item">
              <span>{{ user.name }}</span>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-close"
                @click="removeUser(user)">
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {userTree} from "@/api/system/user";

export default {
  name: 'userBook',
  props: {
    // 控制弹窗显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 控制弹窗显示/隐藏
    multiple: {
      type: Boolean,
      default: true
    },
    // 默认选中的人员
    defaultSelected: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      filterText: '',
      // 组织树数据
      orgTreeData: [],
      // 树形组件配置
      treeProps: {
        children: 'children',
        label: 'name'
      },
      // 已选用户
      selectedUsers: [],
      expandedKeys:['D_100']
    }
  },
  watch: {
    filterText(val) {
      this.$refs.orgTree.filter(val);
    },
    // 监听默认选中人员变化
    defaultSelected: {
      handler(newVal) {
        this.selectedUsers = [...newVal];
        this.updateTreeSelection();
      },
      immediate: true,
      deep: true
    },
    // 监听弹窗显示状态
    visible(newVal) {
      if (newVal) {
        // 弹窗打开时，初始化选中状态和展开状态
        this.$nextTick(() => {
          this.updateTreeSelection();
          // 确保选中的节点是展开的
          this.expandSelectedNodes();
        });
      }
    },
  },
  computed: {
    // 计算属性，用于双向绑定弹窗显示状态
    userBookVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    }
  },
  created() {
    this.getUserTree();
  },
  methods: {
    getUserTree() {
      userTree().then(res => {
        this.orgTreeData = res.data;
      })
    },
    // 过滤树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    }, // 处理节点选中状态变化
    handleCheckChange(data, checked, indeterminate) {
      // 如果是叶子节点（人员）并且被选中
      if (data.checkbox && checked) {
        if(this.multiple){
          // 避免重复添加
          if (!this.selectedUsers.find(user => user.id === data.id)) {
            this.selectedUsers.push({
              id: data.id,
              name: data.name
            });
          }
        }else{
          // 确保只有一个用户被选中
          this.selectedUsers = [{
            id: data.id,
            name: data.name
          }];
          this.updateTreeSelection()
        }
      }
      // 如果是叶子节点（人员）并且取消选中
      if (data.checkbox && !checked) {
        const index = this.selectedUsers.findIndex(user => user.id === data.id);
        if (index > -1) {
          this.selectedUsers.splice(index, 1);
        }
      }
    },
    // 移除已选用户
    removeUser(user) {
      // 从已选列表中移除
      const index = this.selectedUsers.findIndex(u => u.id === user.id);
      if (index > -1) {
        this.selectedUsers.splice(index, 1);
      }

      // 取消树中对应节点的选中状态
      this.$refs.orgTree.setChecked(user.id, false, false);
    },
    // 处理弹窗关闭
    handleClose(done) {
      this.resetSelection();
      this.userBookVisible = false;
    },
    // 更新树的选择状态
    updateTreeSelection() {
      if (this.$refs.orgTree) {
        // 清除所有选中状态
        this.$refs.orgTree.setCheckedKeys([]);
        // 设置当前选中的人员
        const selectedKeys = this.selectedUsers.map(user => user.id);
        this.$refs.orgTree.setCheckedKeys(selectedKeys);
      }
    },
    // 展开选中的节点
    expandSelectedNodes() {
      if (this.selectedUsers.length > 0 && this.$refs.orgTree) {
        // 获取所有选中节点的父节点
        const parentNodes = new Set();

        this.selectedUsers.forEach(user => {
          const node = this.$refs.orgTree.getNode(user.id);
          if (node && node.parent) {
            // 添加所有父节点到展开列表中
            let parent = node.parent;
            while (parent && parent.data && parent.data.id !== 0) { // 0是根节点
              parentNodes.add(parent.data.id);
              parent = parent.parent;
            }
          }
        });

        // 更新展开的节点
        this.expandedKeys = Array.from(parentNodes);

        // 确保根节点总是展开的
        if (!this.expandedKeys.includes('D_100')) {
          this.expandedKeys.push('D_100');
        }
      }
    },

    // 处理节点展开
    handleNodeExpand(data) {
      if (!this.expandedKeys.includes(data.id)) {
        this.expandedKeys.push(data.id);
      }
    },

    // 处理节点折叠
    handleNodeCollapse(data) {
      const index = this.expandedKeys.indexOf(data.id);
      if (index > -1) {
        this.expandedKeys.splice(index, 1);
      }
    },
    // 取消选择
    handleCancel() {
      this.resetSelection();
      this.userBookVisible = false;
    },

    // 确认选择
    handleConfirm() {
      // 在实际应用中，这里可以将选中的用户数据传递给父组件或进行其他处理
      this.$emit('confirm', [...this.selectedUsers]);
      this.userBookVisible = false;
    },

    // 重置选择状态
    resetSelection() {
      // 恢复为默认选中状态
      this.selectedUsers = [...this.defaultSelected];
      this.updateTreeSelection();
    },
  }
}
</script>
<style scoped lang="scss">

.selected-users-preview {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-users-preview h3 {
  margin-top: 0;
  color: #606266;
}

.selected-user-tag {
  margin: 5px;
}

/* 组织人员选择器样式 */
.organization-selector {
  display: flex;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.organization-tree {
  flex: 1;
  padding: 15px;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.selected-panel {
  width: 300px;
  padding: 15px;
  background-color: #f5f7fa;
}

.selected-title {
  margin-bottom: 15px;
  font-weight: bold;
  color: #606266;
}

.selected-list {
  min-height: 200px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.empty-selected {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.svg-icon {
  fill: green!important;
}
</style>
